<template>
    <div>
         <el-drawer
            :title="title+'广告位投放'"
            :visible.sync="drawer"
            :before-close="handleClose"
            custom-class="demo-drawer"
            ref="drawer"
             size="90%">
              <div class="demo-drawer__content">
                    <div class="demo-drawer__content_from">
                        <div class="from">
                            <el-scrollbar wrap-class="scrollbar-wrapper "  ref="resetScroll"   >
                                <el-form :model="userForm" :rules="rules" ref="userForm"  label-width="120px" >
                                    <div class="bt_h2">基本信息</div>
                                    <el-form-item label="名称：" prop="name">
                                        <el-input v-model="userForm.name"></el-input>
                                    </el-form-item>
                                    <el-form-item label="载体类型：" >
                                        <el-radio-group  v-model="userForm.flow_type" size="medium" @input="radio">
                                            <el-radio-button label="1" >pc</el-radio-button>
                                            <el-radio-button label="2">移动</el-radio-button>
                                        </el-radio-group>
                                    </el-form-item>
                                    <el-form-item label="目标代码位：" >
                                        <div class="tablebox">
                                            <div class="table_default table_">
                                                <div class="bt_">目标代码位 
                                                    <el-link type="primary" @click="rowclick_add_all" class="fr" :underline="false">全部添加</el-link>
                                                </div>
                                                <el-table height="300"   :data="codetable.filter(data => !codetablesearch || data.name.toLowerCase().includes(codetablesearch.toLowerCase()))"  @row-click="rowclick_add"  style="width: 100%">
                                                        <el-table-column label="ID" prop="id" width="50"></el-table-column>
                                                        <el-table-column label="代码位名称" prop="name" ></el-table-column>
                                                        <el-table-column label="尺寸"  width="60"></el-table-column>
                                                        <el-table-column align="center" width="150">
                                                            <template slot="header"  slot-scope="scope" >
                                                                <el-input
                                                                v-model="codetablesearch"
                                                                :data="scope"
                                                                size="mini"
                                                                placeholder="输入关键字搜索"/>
                                                            </template>
                                                            <template  slot-scope="{ row }"  >
                                                                    <p>{{ row.c_width }}*{{ row.c_height }} </p>
                                                            </template>
                                                        </el-table-column>
                                                </el-table>
                                            </div>
                                            <div class="table_active table_">
                                                <div class="bt_">已选择（{{userForm.advlist.length}}） 
                                                    <el-link type="primary" class="fr" :underline="false" @click="rowclick_remove_all" >删除全部</el-link>
                                                </div>
                                                <el-table height="300" :show-header="false"     :data="commonProperties"  style="width: 100%">
                                                        <el-table-column    prop="name" width="150"></el-table-column>
                                                        <el-table-column  prop="size" align="right"  width="100"></el-table-column>
                                                        <el-table-column width="50" >
                                                            <template slot-scope="{ row, $index }">
                                                                <i class="el-icon-delete"  @click="rowclick_remove(row,$index)"></i>
                                                            </template>
                                                        </el-table-column>
                                                </el-table>
                                            </div>
                                        </div>
                                    </el-form-item>
                                    <div class="bt_h2">投放设置</div>
                                    <el-form-item label="投放时间：" >
                                        <div class="p_line">
                                            <el-switch
                                                style="display: block"
                                                v-model="userForm.timetype"
                                                active-color="#13ce66"
                                                inactive-color="#1890ff"
                                                :active-value="1"
                                                :inactive-value="0"
                                                active-text="设定结束时间 "
                                                inactive-text="不限制结束时间">
                                            </el-switch>
                                            <el-date-picker
                                                v-show="userForm.timetype==0"
                                                type="datetime"
                                                v-model="start_time"
                                                placeholder="选择日期时间">
                                            </el-date-picker>
                                            <!--   default-time="00:00:00 " -->
                                            <el-date-picker 
                                               v-show="userForm.timetype==1"
                                                type="datetimerange"
                                             
                                                v-model="time_star_end"
                                                start-placeholder="开始日期"
                                                 value-format="yyyy-MM-dd HH:mm:ss"
                                                end-placeholder="结束日期"
                                                >
                                            </el-date-picker>
                                            <!--    :default-time="['00:00:00','00:00:00']" -->
                                        </div>
                                    </el-form-item>
                                    <el-form-item label="优先级："   >
                                        <div class="select_box">
                                            <el-select v-model="userForm.weight1" filterable placeholder="请选择">
                                                <el-option
                                                v-for="item in select_priority_1"
                                                :key="item.value"
                                                :label="item.value"
                                                :value="item.label">
                                                </el-option>
                                            </el-select>
                                            <el-tooltip placement="bottom-end" popper-class="popperClass" >
                                                <div slot="content">
                                                    优先级决定广告的展现顺序。 <br/>
                                                    优先级：独占&gt;优先&gt;标准&gt;补余。 <br/>
                                                    1、独占（1）：优先级最高。通常用于较重要的直投广告。 <br/> 
                                                    2、优先（2-11）：优先级次高。通常用于广告客户直投广告。  <br/>
                                                    3、标准（12-21）：系统默认的优先级。  <br/>
                                                    4、补余（22-29）：优先级最低，通常用于打底的竞价广告，在没有直投广告的时候保障收益。或者用于媒体自身运营的抄底广告。
                                                </div>
                                                <div class="ico">?</div>
                                            </el-tooltip>
                                            <el-select v-model="userForm.weight2" filterable placeholder="请选择">
                                                <el-option
                                                    v-for="item in 29"
                                                    :key="item.value"
                                                    :label="item"
                                                    :value="item">
                                                </el-option>
                                            </el-select>
                                            <el-tooltip placement="bottom-end" popper-class="popperClass">
                                                <div slot="content">
                                                    1（最高）<br>29（最低）
                                                </div>
                                                <div class="ico">?</div>
                                            </el-tooltip>
                                        </div>
                                    </el-form-item>
                                    <el-form-item label="权重：" >
                                        <div class="select_box">
                                            <el-select v-model="userForm.weight3" filterable placeholder="请选择">
                                                <el-option
                                                    v-for="item in 10"
                                                    :key="item.value"
                                                    :label="item"
                                                    :value="item">
                                                </el-option>
                                            </el-select>
                                            <el-tooltip placement="bottom-end" popper-class="popperClass"  >
                                                <div slot="content">
                                                    权重：优先级相同时，高权重的广告的展现概率更高。
                                                </div>
                                                <div class="ico">?</div>
                                            </el-tooltip>
                                        </div>
                                    </el-form-item>
                                    <el-form-item label="总投放量：" >
                                        <el-input v-model="userForm.total_limit" placeholder="不限制则为0"></el-input>
                                    </el-form-item>
                                    <el-form-item label="日投放量：" >
                                        <el-input v-model="userForm.day_limit" placeholder="不限制则为0"></el-input>
                                    </el-form-item>
                                    <el-form-item label="每小时频次：" >
                                        <el-input v-model="userForm.hour_frequency" placeholder="不限制则为0"></el-input>
                                    </el-form-item>
                                    <el-form-item label="每30分钟频次：" >
                                        <el-input v-model="userForm.minute30_frequency" placeholder="不限制则为0"></el-input>
                                    </el-form-item>
                                    <el-form-item label="每20分钟频次：" >
                                        <el-input v-model="userForm.minute20_frequency" placeholder="不限制则为0"></el-input>
                                    </el-form-item>
                                    <el-form-item label="每10分钟频次：" >
                                        <el-input v-model="userForm.minute10_frequency" placeholder="不限制则为0"></el-input>
                                    </el-form-item>
                                    <el-form-item label="每分钟频次：" >
                                        <el-input v-model="userForm.minute_frequency" placeholder="不限制则为0"></el-input>
                                    </el-form-item>
                                    <div class="bt_h2">定向设置</div>
                                    <el-form-item label="物料切换：" >
                                        <el-select v-model="userForm.rotate_type" filterable placeholder="请选择">
                                            <el-option
                                                v-for="item in select_material"
                                                :key="item.label"
                                                :label="item.value"
                                                :value="item.label">
                                            </el-option>
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="幻灯片时间间隔" v-show="userForm.rotate_type==2" >
                                        <el-input v-model="userForm.rotate_val" placeholder="设置幻灯片的时间"></el-input>
                                    </el-form-item>
                                     <!-- 
                                      <el-form-item label="	投放日程" >
                                        <el-input v-model="userForm.schedule_val" placeholder="不限制则为0"></el-input>
                                    </el-form-item> -->
                                    <el-form-item label="广告物料：" >
                                            <div class="tablebox">
                                            <div class=" table_material">
                                                <el-button size="small"  type="primary"  @click='drawer_mateiral_tabler=!drawer_mateiral_tabler'>从物料库选择</el-button>
                                                <el-table   border      :data="userForm.matterlist.filter((item,index,arr) =>  index===arr.findIndex(j=>j.matter_id===item.matter_id) )"        style="width: 100%" v-if="userForm.matterlist.length>0">
                                                        <el-table-column label="物料名称" prop="name" ></el-table-column>
                                                        <el-table-column label="类型"  align="center" width="200"  >
                                                            <template  slot-scope="{ row }" >
                                                                <!-- <div v-if="isValidUrl(row.img)">
                                                                    <el-image :src="row.img" fit="scale-down"></el-image>  
                                                                </div> -->
                                                                <p>{{ row.type }}</p>
                                                            </template>
                                                        </el-table-column>
                                                        <el-table-column label="权重" align="center" width="90">
                                                            <template  slot-scope="{ row }" >
                                                                <el-select v-model="row.weight" size="mini" filterable placeholder="请选择">
                                                                    <el-option
                                                                    v-for="item in 10"
                                                                        :key="item.value"
                                                                        :label="item"
                                                                        :value="item">
                                                                    </el-option>
                                                                </el-select>
                                                            </template>
                                                        </el-table-column>
                                                        <el-table-column label="操作" align="center"  width="60">
                                                            <template   slot-scope="{ row,$index }"  >
                                                                <el-button size="mini" icon="el-icon-delete" type="danger" @click="remove_material(row,$index)"></el-button>
                                                            </template>
                                                        </el-table-column>
                                                </el-table>
                                            </div>
                                        </div>
                                    </el-form-item>
                                </el-form>
                            </el-scrollbar>
                        </div>
                        <div class="demo-drawer__footer">
                            <el-button type="primary"  @click="submitForm('userForm')" :loading="loading">{{ loading ? '提交中 ...' : title=="新建"? '新 建' :'修 改' }}</el-button>
                            <el-button @click="handleClose">取 消</el-button>
                        </div>
                    </div>
                    <el-drawer
                        v-if="drawer_mateiral_tabler"
                        title="选择广告物料"
                        :append-to-body="true"
                        :visible.sync="drawer_mateiral_tabler"
                        :before-close="handleClose_mateiral_tabler"
                        custom-class="demo-drawer"
                        ref="drawer_mateiral_tabler"
                        size="90%">
                        <div class="demo-drawer__content">
                            <div class="demo-drawer__content_from">
                                <div class="mateiraltable">
                                    <el-scrollbar wrap-class="scrollbar-wrapper "  ref="resetScroll2">
                                        <mateiral-table   ref="child" :drawer_mateiral_tabler='drawer_mateiral_tabler' @multipleSelection="matterlistfun"></mateiral-table>
                                    </el-scrollbar>
                                </div>
                                  <div class="demo-drawer__footer">
                                    <el-button type="primary"  @click="determine">确 定</el-button>
                                    <el-button @click="handleClose_mateiral_tabler">取 消</el-button>
                                </div>
                            </div>
                        </div>
                    </el-drawer>
                </div>
         </el-drawer>
        
    </div>
</template>

<script>
import mateiralTable from "@/views/putIn/material.vue"
import { axios_adversense , axios_adsenseinfo ,axios_adver_update} from "@/api/infor";

export default {
    name:'drawer_Code',
    data(){
        return{
            loading:false,
            rules:{
                name: [
                    { required: true, message: '请输入代码位名称', trigger: 'blur' }
                ] 
            },
            drawer_mateiral_tabler:false,  
            time_star_end:[],
            start_time:'',
            userForm:{
                adver_type:'' , //1添加 2修改 3 删除
                id: "",      //id
                name: "",    //名称
                advlist:[], //目标代码位
                created_at:  "", //记录添加时间
                day_limit: "0", //日投放量：
                start_time: "", //广告开始时间
                end_time: "", //广告结束时间
                flow_type: "1", //	载体类型
                matterlist: [],   //物料数组列表
                hour_frequency: "0",    //每小时频次：
                minute10_frequency: "0", //每30分钟频次：
                minute20_frequency: "0",//每20分钟频次：
                minute30_frequency: "0", //每10分钟频次：
                minute_frequency: "0", //每分钟频次：
                priority_id: "",    //优先级编号
                region_type: "0",   //	地域定向类型
                region_val: "",     //地域定向值多个值用逗号拼接多一个,方便查询
                rotate_type:'0',    //	物料轮换
                rotate_val: "0",     //	物料幻灯片轮换时间间隔(秒)
                schedule_val: "",    //投放日程值(0表示全日程)多个投放日程用逗号拼接多一个,方便查询
                status: "",         //记录状态:1启用0停用2投放完成3待投放4暂停
                timetype:1,        //是否有结束
                total_limit: "0", //总投放量：
                updated_at: "", //	记录更新时间
                weight1: 3,//优先级 1
                weight2: 17,//优先级 2
                weight3:5,//权重 
            },
            matterlist_Storage:[],  //默认得值
            select_priority_1:[   //优先级选项
                {value: '独占',label:1},
                {value: '优先',label:2},
                {value: '标准',label:3},
                {value: '补余',label:4},
            ],
            select_material:[  //物料切换选项
                {value: '均匀',label:'0'},
                {value: '手动权重',label: '1'},
                {value: '幻灯片轮换',label: '2'},
                {value: '微轮播',label: '3'},
            ],
            codetablesearch:'',  //代码位搜索
            codetable:[ ],//全部得代码位
         
        }
    },
    components:{
        mateiralTable
    },
    props:{
        drawer:{
            type: Boolean,
            default:false,
        },
        id:{},
        title:{},
    },
    computed:{
       datawatch(){
          let title=this.title
          let id=this.id;
          let drawer=this.drawer;
          return {title,id,drawer}
       },
       commonProperties(){
         const common = this.codetable.filter(item1 =>
            this.userForm.advlist.some(item2 => item2.id === item1.id)
         );
        return common;
       },
       materialval(){
          let val='';
           this.userForm.rotate_type==0? val='均匀' : this.userForm.rotate_type==1? val='手动权重' : this.userForm.rotate_type==2? val='幻灯片轮换' :  val='微轮播'
          return val;
       },
        starttime_cpu(){
            return this.$formateDate(this.userForm.start_time);
        },
         endtime_cpu(){
            return this.$formateDate(this.userForm.end_time);
        },
        timestarend__cpu(){
             return [this.$formateDate(this.userForm.start_time),this.$formateDate(this.userForm.end_time)];
        }
    },
    watch:{
        datawatch:{
            immediate:true,
            handler(n){
                if(n.drawer){
                    Object.assign(this.$data,this.$options.data.call(this));
                     this.getaxios_adversense();
                     if( n.id!=''){
                        this.getaxios_adsenseinfo(4,n.id)  ;
                        
                    }
                } 
            }
        },
        drawer(a){
            if(a){
                this.$nextTick(()=>{
                    this.$refs.resetScroll.wrap.scrollTop=0;
                    this.$refs["userForm"].clearValidate();
                })
            }
        },
        drawer_mateiral_tabler(a){
            if(a){
                this.$nextTick(()=>{
                    this.$refs.resetScroll2.wrap.scrollTop=0;
                })
            }
        },
        
    },
    created(){
    },
    methods:{
        radio(){
            this.getaxios_adversense()
        },
        isValidUrl(url) {
            const regex = /^https?:\/\/(?:www\.)?[^\s/$.?#].[^\s]*/;
            return regex.test(url);
        },
        matterlistfun(data){
              this.matterlist_Storage=[];
            data.forEach((item)=>{
                let ite={weight:5,matter_id:Number(item.id),name:item.name,type:item.type}
                this.matterlist_Storage.push(ite);
            })
        },
        determine(){
           this.matterlist_Storage.forEach((item)=>{
                 this.userForm.matterlist.push(item);
            })
            this.handleClose_mateiral_tabler();
        },
         //关闭广告位代码
        handleClose(){
            this.$emit("handleClose",this.drawer)
        },
        handleClose_mateiral_tabler(){
            this.drawer_mateiral_tabler=false;
            this.$refs.child.multipleSelection=[];
            this.$refs.child.$refs.multipleTable.clearSelection();
            this.$nextTick(() => {
                const element = this.$refs.resetScroll.wrap;
                if (element) {
                    element.scrollTop = element.scrollHeight - element.clientHeight;
                }
            });
        },
        // 定位代码位得尺寸
        rowclick_add_all(){
            this.userForm.advlist=this.codetable;
        },
        rowclick_remove_all(){
            this.userForm.advlist=[];
        },
        rowclick_add(row ){
          if(!this.userForm.advlist.includes(row)){
            this.userForm.advlist.push( row)
          }
        },
        rowclick_remove(row,index){
          this.userForm.advlist.splice( index,1);
          if(this.userForm.advlist.length==0){
               this.userForm.advlist=[];
          }
        },
        remove_material(row,index){
            this.$confirm('确定移除此条物料内容吗？','移除物料',{customClass:'layeralterelbox'}) .then(()  => {
                this.userForm.matterlist.splice(index,1)
             }).catch(()  => {});
        },
          // 提交个人信息
          submitForm(formName){
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    //  this.loading = true;
                    if(this.title=="修改"){
                        this.userForm.adver_type=2
                    }else{
                        this.userForm.adver_type=1
                    }
                    this.userForm.start_time=new Date(this.start_time).getTime()/1000;
                    if(this.userForm.timetype==1){
                        this.userForm.end_time= new Date(this.time_star_end[1]).getTime()/1000;
                    }else{
                         this.userForm.end_time='0';
                    }
                     if(this.userForm.advlist==[]){
                        this.userForm.advlist=''
                    }
                    axios_adver_update(this.userForm).then((res) => {
                        if(res.data.code==1){
                             this.loading = false;
                             this.handleClose() //关闭
                              this.$emit("adputinUpdate",true)
                        }
                    }).catch(( )=>{})
                } else {
                    return false;
                }
            });
        },
        // 获取广告详情
        getaxios_adsenseinfo(type,id){
            axios_adsenseinfo({type:type, ad_id:id}).then((res) => {
                if(res.data.code==1){
                    this.userForm=res.data.data[0];
                    if(this.userForm.advlist==''){
                        this.userForm.advlist=[]
                    }
                    this.start_time=this.starttime_cpu;
                    this.time_star_end=this.timestarend__cpu;
                }
            }).catch(( )=>{})
        },
        // 获取目标代码位
        getaxios_adversense(){
                axios_adversense({model:2, flow_type:this.userForm.flow_type}).then((res) => {
                if(res.data.code==1){
                    this.codetable=res.data.data;
                }
            }).catch(( )=>{})
        }
    }
}
</script>
<style lang="scss" scoped>
.mateiraltable{
     padding: 0 20px;
    flex: 1;
    overflow: hidden;
    .el-scrollbar{
        height:100%;
    }
}
</style>